
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta charset="utf-8" />
    <title>7. Input and Output &#8212; Python 3.8.13 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <link rel="stylesheet" href="../_static/pydoctheme.css?2022.1" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script src="../_static/jquery.js"></script>
    <script src="../_static/underscore.js"></script>
    <script src="../_static/doctools.js"></script>
    <script src="../_static/language_data.js"></script>
    
    <script src="../_static/sidebar.js"></script>
    
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 3.8.13 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="8. Errors and Exceptions" href="errors.html" />
    <link rel="prev" title="6. Modules" href="modules.html" />
    <link rel="canonical" href="https://docs.python.org/3/tutorial/inputoutput.html" />
    
      
    

    
    <style>
      @media only screen {
        table.full-width-table {
            width: 100%;
        }
      }
    </style>
<link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
            <script type="text/javascript" src="../_static/copybutton.js"></script>
            <script type="text/javascript" src="../_static/menu.js"></script> 

  </head>
<body>
<div class="mobile-nav">
    <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
           aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
    <label for="menuToggler" class="toggler__label">
        <span></span>
    </label>
    <nav class="nav-content" role="navigation">
         <a href="https://www.python.org/" class="nav-logo">
             <img src="../_static/py.svg" alt="Logo"/>
         </a>
        <div class="version_switcher_placeholder"></div>
        <form role="search" class="search" action="../search.html" method="get">
            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
                <path fill-rule="nonzero"
                        d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z" fill="#444"></path>
            </svg>
            <input type="text" name="q" aria-label="Quick search"/>
            <input type="submit" value="Go"/>
        </form>
    </nav>
    <div class="menu-wrapper">
        <nav class="menu" role="navigation" aria-label="main navigation">
            <div class="language_switcher_placeholder"></div>
  <h3><a href="../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">7. Input and Output</a><ul>
<li><a class="reference internal" href="#fancier-output-formatting">7.1. Fancier Output Formatting</a><ul>
<li><a class="reference internal" href="#formatted-string-literals">7.1.1. Formatted String Literals</a></li>
<li><a class="reference internal" href="#the-string-format-method">7.1.2. The String format() Method</a></li>
<li><a class="reference internal" href="#manual-string-formatting">7.1.3. Manual String Formatting</a></li>
<li><a class="reference internal" href="#old-string-formatting">7.1.4. Old string formatting</a></li>
</ul>
</li>
<li><a class="reference internal" href="#reading-and-writing-files">7.2. Reading and Writing Files</a><ul>
<li><a class="reference internal" href="#methods-of-file-objects">7.2.1. Methods of File Objects</a></li>
<li><a class="reference internal" href="#saving-structured-data-with-json">7.2.2. Saving structured data with <code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="modules.html"
                        title="previous chapter"><span class="section-number">6. </span>Modules</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="errors.html"
                        title="next chapter"><span class="section-number">8. </span>Errors and Exceptions</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../bugs.html">Report a Bug</a></li>
      <li>
        <a href="https://github.com/python/cpython/blob/3.8/Doc/tutorial/inputoutput.rst"
            rel="nofollow">Show Source
        </a>
      </li>
    </ul>
  </div>
        </nav>
    </div>
</div>

  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="errors.html" title="8. Errors and Exceptions"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="modules.html" title="6. Modules"
             accesskey="P">previous</a> |</li>

          <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
          <li><a href="https://www.python.org/">Python</a> &#187;</li>
          <li class="switchers">
            <div class="language_switcher_placeholder"></div>
            <div class="version_switcher_placeholder"></div>
          </li>
          <li>
              
          </li>
    <li id="cpython-language-and-version">
      <a href="../index.html">3.8.13 Documentation</a> &#187;
    </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li>
                <li class="right">
                    

    <div class="inline-search" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="Quick search" aria-label="Quick search" type="text" name="q" />
          <input type="submit" value="Go" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
                     |
                </li>
            
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="input-and-output">
<span id="tut-io"></span><h1><span class="section-number">7. </span>Input and Output<a class="headerlink" href="#input-and-output" title="Permalink to this headline">¶</a></h1>
<p>There are several ways to present the output of a program; data can be printed
in a human-readable form, or written to a file for future use. This chapter will
discuss some of the possibilities.</p>
<div class="section" id="fancier-output-formatting">
<span id="tut-formatting"></span><h2><span class="section-number">7.1. </span>Fancier Output Formatting<a class="headerlink" href="#fancier-output-formatting" title="Permalink to this headline">¶</a></h2>
<p>So far we’ve encountered two ways of writing values: <em>expression statements</em> and
the <a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> function.  (A third way is using the <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> method
of file objects; the standard output file can be referenced as <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code>.
See the Library Reference for more information on this.)</p>
<p>Often you’ll want more control over the formatting of your output than simply
printing space-separated values. There are several ways to format output.</p>
<ul>
<li><p>To use <a class="reference internal" href="#tut-f-strings"><span class="std std-ref">formatted string literals</span></a>, begin a string
with <code class="docutils literal notranslate"><span class="pre">f</span></code> or <code class="docutils literal notranslate"><span class="pre">F</span></code> before the opening quotation mark or triple quotation mark.
Inside this string, you can write a Python expression between <code class="docutils literal notranslate"><span class="pre">{</span></code> and <code class="docutils literal notranslate"><span class="pre">}</span></code>
characters that can refer to variables or literal values.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">year</span> <span class="o">=</span> <span class="mi">2016</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">event</span> <span class="o">=</span> <span class="s1">&#39;Referendum&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="sa">f</span><span class="s1">&#39;Results of the </span><span class="si">{</span><span class="n">year</span><span class="si">}</span><span class="s1"> </span><span class="si">{</span><span class="n">event</span><span class="si">}</span><span class="s1">&#39;</span>
<span class="go">&#39;Results of the 2016 Referendum&#39;</span>
</pre></div>
</div>
</li>
<li><p>The <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method of strings requires more manual
effort.  You’ll still use <code class="docutils literal notranslate"><span class="pre">{</span></code> and <code class="docutils literal notranslate"><span class="pre">}</span></code> to mark where a variable
will be substituted and can provide detailed formatting directives,
but you’ll also need to provide the information to be formatted.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">yes_votes</span> <span class="o">=</span> <span class="mi">42_572_654</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">no_votes</span> <span class="o">=</span> <span class="mi">43_132_495</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">percentage</span> <span class="o">=</span> <span class="n">yes_votes</span> <span class="o">/</span> <span class="p">(</span><span class="n">yes_votes</span> <span class="o">+</span> <span class="n">no_votes</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">{:-9}</span><span class="s1"> YES votes  </span><span class="si">{:2.2%}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">yes_votes</span><span class="p">,</span> <span class="n">percentage</span><span class="p">)</span>
<span class="go">&#39; 42572654 YES votes  49.67%&#39;</span>
</pre></div>
</div>
</li>
<li><p>Finally, you can do all the string handling yourself by using string slicing and
concatenation operations to create any layout you can imagine.  The
string type has some methods that perform useful operations for padding
strings to a given column width.</p></li>
</ul>
<p>When you don’t need fancy output but just want a quick display of some
variables for debugging purposes, you can convert any value to a string with
the <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> or <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> functions.</p>
<p>The <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> function is meant to return representations of values which are
fairly human-readable, while <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> is meant to generate representations
which can be read by the interpreter (or will force a <a class="reference internal" href="../library/exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> if
there is no equivalent syntax).  For objects which don’t have a particular
representation for human consumption, <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> will return the same value as
<a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a>.  Many values, such as numbers or structures like lists and
dictionaries, have the same representation using either function.  Strings, in
particular, have two distinct representations.</p>
<p>Some examples:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;Hello, world.&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">str</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="go">&#39;Hello, world.&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">repr</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="go">&quot;&#39;Hello, world.&#39;&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">str</span><span class="p">(</span><span class="mi">1</span><span class="o">/</span><span class="mi">7</span><span class="p">)</span>
<span class="go">&#39;0.14285714285714285&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="mi">10</span> <span class="o">*</span> <span class="mf">3.25</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="mi">200</span> <span class="o">*</span> <span class="mi">200</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;The value of x is &#39;</span> <span class="o">+</span> <span class="nb">repr</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="o">+</span> <span class="s1">&#39;, and y is &#39;</span> <span class="o">+</span> <span class="nb">repr</span><span class="p">(</span><span class="n">y</span><span class="p">)</span> <span class="o">+</span> <span class="s1">&#39;...&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="go">The value of x is 32.5, and y is 40000...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># The repr() of a string adds string quotes and backslashes:</span>
<span class="gp">... </span><span class="n">hello</span> <span class="o">=</span> <span class="s1">&#39;hello, world</span><span class="se">\n</span><span class="s1">&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">hellos</span> <span class="o">=</span> <span class="nb">repr</span><span class="p">(</span><span class="n">hello</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">hellos</span><span class="p">)</span>
<span class="go">&#39;hello, world\n&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># The argument to repr() may be any Python object:</span>
<span class="gp">... </span><span class="nb">repr</span><span class="p">((</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="p">(</span><span class="s1">&#39;spam&#39;</span><span class="p">,</span> <span class="s1">&#39;eggs&#39;</span><span class="p">)))</span>
<span class="go">&quot;(32.5, 40000, (&#39;spam&#39;, &#39;eggs&#39;))&quot;</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> module contains a <a class="reference internal" href="../library/string.html#string.Template" title="string.Template"><code class="xref py py-class docutils literal notranslate"><span class="pre">Template</span></code></a> class that offers
yet another way to substitute values into strings, using placeholders like
<code class="docutils literal notranslate"><span class="pre">$x</span></code> and replacing them with values from a dictionary, but offers much less
control of the formatting.</p>
<div class="section" id="formatted-string-literals">
<span id="tut-f-strings"></span><h3><span class="section-number">7.1.1. </span>Formatted String Literals<a class="headerlink" href="#formatted-string-literals" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="../reference/lexical_analysis.html#f-strings"><span class="std std-ref">Formatted string literals</span></a> (also called f-strings for
short) let you include the value of Python expressions inside a string by
prefixing the string with <code class="docutils literal notranslate"><span class="pre">f</span></code> or <code class="docutils literal notranslate"><span class="pre">F</span></code> and writing expressions as
<code class="docutils literal notranslate"><span class="pre">{expression}</span></code>.</p>
<p>An optional format specifier can follow the expression. This allows greater
control over how the value is formatted. The following example rounds pi to
three places after the decimal:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">math</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;The value of pi is approximately </span><span class="si">{</span><span class="n">math</span><span class="o">.</span><span class="n">pi</span><span class="si">:</span><span class="s1">.3f</span><span class="si">}</span><span class="s1">.&#39;</span><span class="p">)</span>
<span class="go">The value of pi is approximately 3.142.</span>
</pre></div>
</div>
<p>Passing an integer after the <code class="docutils literal notranslate"><span class="pre">':'</span></code> will cause that field to be a minimum
number of characters wide.  This is useful for making columns line up.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">table</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;Sjoerd&#39;</span><span class="p">:</span> <span class="mi">4127</span><span class="p">,</span> <span class="s1">&#39;Jack&#39;</span><span class="p">:</span> <span class="mi">4098</span><span class="p">,</span> <span class="s1">&#39;Dcab&#39;</span><span class="p">:</span> <span class="mi">7678</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">name</span><span class="p">,</span> <span class="n">phone</span> <span class="ow">in</span> <span class="n">table</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">name</span><span class="si">:</span><span class="s1">10</span><span class="si">}</span><span class="s1"> ==&gt; </span><span class="si">{</span><span class="n">phone</span><span class="si">:</span><span class="s1">10d</span><span class="si">}</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">Sjoerd     ==&gt;       4127</span>
<span class="go">Jack       ==&gt;       4098</span>
<span class="go">Dcab       ==&gt;       7678</span>
</pre></div>
</div>
<p>Other modifiers can be used to convert the value before it is formatted.
<code class="docutils literal notranslate"><span class="pre">'!a'</span></code> applies <a class="reference internal" href="../library/functions.html#ascii" title="ascii"><code class="xref py py-func docutils literal notranslate"><span class="pre">ascii()</span></code></a>, <code class="docutils literal notranslate"><span class="pre">'!s'</span></code> applies <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a>, and <code class="docutils literal notranslate"><span class="pre">'!r'</span></code>
applies <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">animals</span> <span class="o">=</span> <span class="s1">&#39;eels&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;My hovercraft is full of </span><span class="si">{</span><span class="n">animals</span><span class="si">}</span><span class="s1">.&#39;</span><span class="p">)</span>
<span class="go">My hovercraft is full of eels.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;My hovercraft is full of </span><span class="si">{</span><span class="n">animals</span><span class="si">!r}</span><span class="s1">.&#39;</span><span class="p">)</span>
<span class="go">My hovercraft is full of &#39;eels&#39;.</span>
</pre></div>
</div>
<p>For a reference on these format specifications, see
the reference guide for the <a class="reference internal" href="../library/string.html#formatspec"><span class="std std-ref">Format Specification Mini-Language</span></a>.</p>
</div>
<div class="section" id="the-string-format-method">
<span id="tut-string-format"></span><h3><span class="section-number">7.1.2. </span>The String format() Method<a class="headerlink" href="#the-string-format-method" title="Permalink to this headline">¶</a></h3>
<p>Basic usage of the <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method looks like this:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;We are the </span><span class="si">{}</span><span class="s1"> who say &quot;</span><span class="si">{}</span><span class="s1">!&quot;&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;knights&#39;</span><span class="p">,</span> <span class="s1">&#39;Ni&#39;</span><span class="p">))</span>
<span class="go">We are the knights who say &quot;Ni!&quot;</span>
</pre></div>
</div>
<p>The brackets and characters within them (called format fields) are replaced with
the objects passed into the <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method.  A number in the
brackets can be used to refer to the position of the object passed into the
<a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">{0}</span><span class="s1"> and </span><span class="si">{1}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;spam&#39;</span><span class="p">,</span> <span class="s1">&#39;eggs&#39;</span><span class="p">))</span>
<span class="go">spam and eggs</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">{1}</span><span class="s1"> and </span><span class="si">{0}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;spam&#39;</span><span class="p">,</span> <span class="s1">&#39;eggs&#39;</span><span class="p">))</span>
<span class="go">eggs and spam</span>
</pre></div>
</div>
<p>If keyword arguments are used in the <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method, their values
are referred to by using the name of the argument.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;This </span><span class="si">{food}</span><span class="s1"> is </span><span class="si">{adjective}</span><span class="s1">.&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
<span class="gp">... </span>      <span class="n">food</span><span class="o">=</span><span class="s1">&#39;spam&#39;</span><span class="p">,</span> <span class="n">adjective</span><span class="o">=</span><span class="s1">&#39;absolutely horrible&#39;</span><span class="p">))</span>
<span class="go">This spam is absolutely horrible.</span>
</pre></div>
</div>
<p>Positional and keyword arguments can be arbitrarily combined:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;The story of </span><span class="si">{0}</span><span class="s1">, </span><span class="si">{1}</span><span class="s1">, and </span><span class="si">{other}</span><span class="s1">.&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;Bill&#39;</span><span class="p">,</span> <span class="s1">&#39;Manfred&#39;</span><span class="p">,</span>
<span class="go">                                                       other=&#39;Georg&#39;))</span>
<span class="go">The story of Bill, Manfred, and Georg.</span>
</pre></div>
</div>
<p>If you have a really long format string that you don’t want to split up, it
would be nice if you could reference the variables to be formatted by name
instead of by position.  This can be done by simply passing the dict and using
square brackets <code class="docutils literal notranslate"><span class="pre">'[]'</span></code> to access the keys.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">table</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;Sjoerd&#39;</span><span class="p">:</span> <span class="mi">4127</span><span class="p">,</span> <span class="s1">&#39;Jack&#39;</span><span class="p">:</span> <span class="mi">4098</span><span class="p">,</span> <span class="s1">&#39;Dcab&#39;</span><span class="p">:</span> <span class="mi">8637678</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Jack: </span><span class="si">{0[Jack]:d}</span><span class="s1">; Sjoerd: </span><span class="si">{0[Sjoerd]:d}</span><span class="s1">; &#39;</span>
<span class="gp">... </span>      <span class="s1">&#39;Dcab: </span><span class="si">{0[Dcab]:d}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">table</span><span class="p">))</span>
<span class="go">Jack: 4098; Sjoerd: 4127; Dcab: 8637678</span>
</pre></div>
</div>
<p>This could also be done by passing the table as keyword arguments with the ‘**’
notation.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">table</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;Sjoerd&#39;</span><span class="p">:</span> <span class="mi">4127</span><span class="p">,</span> <span class="s1">&#39;Jack&#39;</span><span class="p">:</span> <span class="mi">4098</span><span class="p">,</span> <span class="s1">&#39;Dcab&#39;</span><span class="p">:</span> <span class="mi">8637678</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Jack: </span><span class="si">{Jack:d}</span><span class="s1">; Sjoerd: </span><span class="si">{Sjoerd:d}</span><span class="s1">; Dcab: </span><span class="si">{Dcab:d}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="o">**</span><span class="n">table</span><span class="p">))</span>
<span class="go">Jack: 4098; Sjoerd: 4127; Dcab: 8637678</span>
</pre></div>
</div>
<p>This is particularly useful in combination with the built-in function
<a class="reference internal" href="../library/functions.html#vars" title="vars"><code class="xref py py-func docutils literal notranslate"><span class="pre">vars()</span></code></a>, which returns a dictionary containing all local variables.</p>
<p>As an example, the following lines produce a tidily-aligned
set of columns giving integers and their squares and cubes:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">11</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">{0:2d}</span><span class="s1"> </span><span class="si">{1:3d}</span><span class="s1"> </span><span class="si">{2:4d}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="p">,</span> <span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="p">))</span>
<span class="gp">...</span>
<span class="go"> 1   1    1</span>
<span class="go"> 2   4    8</span>
<span class="go"> 3   9   27</span>
<span class="go"> 4  16   64</span>
<span class="go"> 5  25  125</span>
<span class="go"> 6  36  216</span>
<span class="go"> 7  49  343</span>
<span class="go"> 8  64  512</span>
<span class="go"> 9  81  729</span>
<span class="go">10 100 1000</span>
</pre></div>
</div>
<p>For a complete overview of string formatting with <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a>, see
<a class="reference internal" href="../library/string.html#formatstrings"><span class="std std-ref">Format String Syntax</span></a>.</p>
</div>
<div class="section" id="manual-string-formatting">
<h3><span class="section-number">7.1.3. </span>Manual String Formatting<a class="headerlink" href="#manual-string-formatting" title="Permalink to this headline">¶</a></h3>
<p>Here’s the same table of squares and cubes, formatted manually:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">11</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="nb">repr</span><span class="p">(</span><span class="n">x</span><span class="p">)</span><span class="o">.</span><span class="n">rjust</span><span class="p">(</span><span class="mi">2</span><span class="p">),</span> <span class="nb">repr</span><span class="p">(</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="p">)</span><span class="o">.</span><span class="n">rjust</span><span class="p">(</span><span class="mi">3</span><span class="p">),</span> <span class="n">end</span><span class="o">=</span><span class="s1">&#39; &#39;</span><span class="p">)</span>
<span class="gp">... </span>    <span class="c1"># Note use of &#39;end&#39; on previous line</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="nb">repr</span><span class="p">(</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="p">)</span><span class="o">.</span><span class="n">rjust</span><span class="p">(</span><span class="mi">4</span><span class="p">))</span>
<span class="gp">...</span>
<span class="go"> 1   1    1</span>
<span class="go"> 2   4    8</span>
<span class="go"> 3   9   27</span>
<span class="go"> 4  16   64</span>
<span class="go"> 5  25  125</span>
<span class="go"> 6  36  216</span>
<span class="go"> 7  49  343</span>
<span class="go"> 8  64  512</span>
<span class="go"> 9  81  729</span>
<span class="go">10 100 1000</span>
</pre></div>
</div>
<p>(Note that the one space between each column was added by the
way <a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> works: it always adds spaces between its arguments.)</p>
<p>The <a class="reference internal" href="../library/stdtypes.html#str.rjust" title="str.rjust"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.rjust()</span></code></a> method of string objects right-justifies a string in a
field of a given width by padding it with spaces on the left. There are
similar methods <a class="reference internal" href="../library/stdtypes.html#str.ljust" title="str.ljust"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.ljust()</span></code></a> and <a class="reference internal" href="../library/stdtypes.html#str.center" title="str.center"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.center()</span></code></a>. These methods do
not write anything, they just return a new string. If the input string is too
long, they don’t truncate it, but return it unchanged; this will mess up your
column lay-out but that’s usually better than the alternative, which would be
lying about a value. (If you really want truncation you can always add a
slice operation, as in <code class="docutils literal notranslate"><span class="pre">x.ljust(n)[:n]</span></code>.)</p>
<p>There is another method, <a class="reference internal" href="../library/stdtypes.html#str.zfill" title="str.zfill"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.zfill()</span></code></a>, which pads a numeric string on the
left with zeros.  It understands about plus and minus signs:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;12&#39;</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
<span class="go">&#39;00012&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;-3.14&#39;</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span>
<span class="go">&#39;-003.14&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;3.14159265359&#39;</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
<span class="go">&#39;3.14159265359&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="old-string-formatting">
<h3><span class="section-number">7.1.4. </span>Old string formatting<a class="headerlink" href="#old-string-formatting" title="Permalink to this headline">¶</a></h3>
<p>The % operator (modulo) can also be used for string formatting. Given <code class="docutils literal notranslate"><span class="pre">'string'</span>
<span class="pre">%</span> <span class="pre">values</span></code>, instances of <code class="docutils literal notranslate"><span class="pre">%</span></code> in <code class="docutils literal notranslate"><span class="pre">string</span></code> are replaced with zero or more
elements of <code class="docutils literal notranslate"><span class="pre">values</span></code>. This operation is commonly known as string
interpolation. For example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">math</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;The value of pi is approximately </span><span class="si">%5.3f</span><span class="s1">.&#39;</span> <span class="o">%</span> <span class="n">math</span><span class="o">.</span><span class="n">pi</span><span class="p">)</span>
<span class="go">The value of pi is approximately 3.142.</span>
</pre></div>
</div>
<p>More information can be found in the <a class="reference internal" href="../library/stdtypes.html#old-string-formatting"><span class="std std-ref">printf-style String Formatting</span></a> section.</p>
</div>
</div>
<div class="section" id="reading-and-writing-files">
<span id="tut-files"></span><h2><span class="section-number">7.2. </span>Reading and Writing Files<a class="headerlink" href="#reading-and-writing-files" title="Permalink to this headline">¶</a></h2>
<p id="index-0"><a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> returns a <a class="reference internal" href="../glossary.html#term-file-object"><span class="xref std std-term">file object</span></a>, and is most commonly used with
two arguments: <code class="docutils literal notranslate"><span class="pre">open(filename,</span> <span class="pre">mode)</span></code>.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;workfile&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>The first argument is a string containing the filename.  The second argument is
another string containing a few characters describing the way in which the file
will be used.  <em>mode</em> can be <code class="docutils literal notranslate"><span class="pre">'r'</span></code> when the file will only be read, <code class="docutils literal notranslate"><span class="pre">'w'</span></code>
for only writing (an existing file with the same name will be erased), and
<code class="docutils literal notranslate"><span class="pre">'a'</span></code> opens the file for appending; any data written to the file is
automatically added to the end.  <code class="docutils literal notranslate"><span class="pre">'r+'</span></code> opens the file for both reading and
writing. The <em>mode</em> argument is optional; <code class="docutils literal notranslate"><span class="pre">'r'</span></code> will be assumed if it’s
omitted.</p>
<p>Normally, files are opened in <em class="dfn">text mode</em>, that means, you read and write
strings from and to the file, which are encoded in a specific encoding. If
encoding is not specified, the default is platform dependent (see
<a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>). <code class="docutils literal notranslate"><span class="pre">'b'</span></code> appended to the mode opens the file in
<em class="dfn">binary mode</em>: now the data is read and written in the form of bytes
objects.  This mode should be used for all files that don’t contain text.</p>
<p>In text mode, the default when reading is to convert platform-specific line
endings (<code class="docutils literal notranslate"><span class="pre">\n</span></code> on Unix, <code class="docutils literal notranslate"><span class="pre">\r\n</span></code> on Windows) to just <code class="docutils literal notranslate"><span class="pre">\n</span></code>.  When writing in
text mode, the default is to convert occurrences of <code class="docutils literal notranslate"><span class="pre">\n</span></code> back to
platform-specific line endings.  This behind-the-scenes modification
to file data is fine for text files, but will corrupt binary data like that in
<code class="file docutils literal notranslate"><span class="pre">JPEG</span></code> or <code class="file docutils literal notranslate"><span class="pre">EXE</span></code> files.  Be very careful to use binary mode when
reading and writing such files.</p>
<p>It is good practice to use the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> keyword when dealing
with file objects.  The advantage is that the file is properly closed
after its suite finishes, even if an exception is raised at some
point.  Using <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> is also much shorter than writing
equivalent <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>-<a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> blocks:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;workfile&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">read_data</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># We can check that the file has been automatically closed.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">closed</span>
<span class="go">True</span>
</pre></div>
</div>
<p>If you’re not using the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> keyword, then you should call
<code class="docutils literal notranslate"><span class="pre">f.close()</span></code> to close the file and immediately free up any system
resources used by it.</p>
<div class="admonition warning">
<p class="admonition-title">Warning</p>
<p>Calling <code class="docutils literal notranslate"><span class="pre">f.write()</span></code> without using the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> keyword or calling
<code class="docutils literal notranslate"><span class="pre">f.close()</span></code> <strong>might</strong> result in the arguments
of <code class="docutils literal notranslate"><span class="pre">f.write()</span></code> not being completely written to the disk, even if the
program exits successfully.</p>
</div>
<p>After a file object is closed, either by a <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement
or by calling <code class="docutils literal notranslate"><span class="pre">f.close()</span></code>, attempts to use the file object will
automatically fail.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">ValueError</span>: <span class="n">I/O operation on closed file.</span>
</pre></div>
</div>
<div class="section" id="methods-of-file-objects">
<span id="tut-filemethods"></span><h3><span class="section-number">7.2.1. </span>Methods of File Objects<a class="headerlink" href="#methods-of-file-objects" title="Permalink to this headline">¶</a></h3>
<p>The rest of the examples in this section will assume that a file object called
<code class="docutils literal notranslate"><span class="pre">f</span></code> has already been created.</p>
<p>To read a file’s contents, call <code class="docutils literal notranslate"><span class="pre">f.read(size)</span></code>, which reads some quantity of
data and returns it as a string (in text mode) or bytes object (in binary mode).
<em>size</em> is an optional numeric argument.  When <em>size</em> is omitted or negative, the
entire contents of the file will be read and returned; it’s your problem if the
file is twice as large as your machine’s memory. Otherwise, at most <em>size</em>
characters (in text mode) or <em>size</em> bytes (in binary mode) are read and returned.
If the end of the file has been reached, <code class="docutils literal notranslate"><span class="pre">f.read()</span></code> will return an empty
string (<code class="docutils literal notranslate"><span class="pre">''</span></code>).</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="go">&#39;This is the entire file.\n&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="go">&#39;&#39;</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">f.readline()</span></code> reads a single line from the file; a newline character (<code class="docutils literal notranslate"><span class="pre">\n</span></code>)
is left at the end of the string, and is only omitted on the last line of the
file if the file doesn’t end in a newline.  This makes the return value
unambiguous; if <code class="docutils literal notranslate"><span class="pre">f.readline()</span></code> returns an empty string, the end of the file
has been reached, while a blank line is represented by <code class="docutils literal notranslate"><span class="pre">'\n'</span></code>, a string
containing only a single newline.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
<span class="go">&#39;This is the first line of the file.\n&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
<span class="go">&#39;Second line of the file\n&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
<span class="go">&#39;&#39;</span>
</pre></div>
</div>
<p>For reading lines from a file, you can loop over the file object. This is memory
efficient, fast, and leads to simple code:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="n">line</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">This is the first line of the file.</span>
<span class="go">Second line of the file</span>
</pre></div>
</div>
<p>If you want to read all the lines of a file in a list you can also use
<code class="docutils literal notranslate"><span class="pre">list(f)</span></code> or <code class="docutils literal notranslate"><span class="pre">f.readlines()</span></code>.</p>
<p><code class="docutils literal notranslate"><span class="pre">f.write(string)</span></code> writes the contents of <em>string</em> to the file, returning
the number of characters written.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;This is a test</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="go">15</span>
</pre></div>
</div>
<p>Other types of objects need to be converted – either to a string (in text mode)
or a bytes object (in binary mode) – before writing them:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">value</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;the answer&#39;</span><span class="p">,</span> <span class="mi">42</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="nb">str</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>  <span class="c1"># convert the tuple to string</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="go">18</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">f.tell()</span></code> returns an integer giving the file object’s current position in the file
represented as number of bytes from the beginning of the file when in binary mode and
an opaque number when in text mode.</p>
<p>To change the file object’s position, use <code class="docutils literal notranslate"><span class="pre">f.seek(offset,</span> <span class="pre">whence)</span></code>.  The position is computed
from adding <em>offset</em> to a reference point; the reference point is selected by
the <em>whence</em> argument.  A <em>whence</em> value of 0 measures from the beginning
of the file, 1 uses the current file position, and 2 uses the end of the file as
the reference point.  <em>whence</em> can be omitted and defaults to 0, using the
beginning of the file as the reference point.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;workfile&#39;</span><span class="p">,</span> <span class="s1">&#39;rb+&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;0123456789abcdef&#39;</span><span class="p">)</span>
<span class="go">16</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">seek</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>      <span class="c1"># Go to the 6th byte in the file</span>
<span class="go">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">b&#39;5&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">seek</span><span class="p">(</span><span class="o">-</span><span class="mi">3</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>  <span class="c1"># Go to the 3rd byte before the end</span>
<span class="go">13</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">b&#39;d&#39;</span>
</pre></div>
</div>
<p>In text files (those opened without a <code class="docutils literal notranslate"><span class="pre">b</span></code> in the mode string), only seeks
relative to the beginning of the file are allowed (the exception being seeking
to the very file end with <code class="docutils literal notranslate"><span class="pre">seek(0,</span> <span class="pre">2)</span></code>) and the only valid <em>offset</em> values are
those returned from the <code class="docutils literal notranslate"><span class="pre">f.tell()</span></code>, or zero. Any other <em>offset</em> value produces
undefined behaviour.</p>
<p>File objects have some additional methods, such as <code class="xref py py-meth docutils literal notranslate"><span class="pre">isatty()</span></code> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">truncate()</span></code> which are less frequently used; consult the Library
Reference for a complete guide to file objects.</p>
</div>
<div class="section" id="saving-structured-data-with-json">
<span id="tut-json"></span><h3><span class="section-number">7.2.2. </span>Saving structured data with <a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a><a class="headerlink" href="#saving-structured-data-with-json" title="Permalink to this headline">¶</a></h3>
<p id="index-1">Strings can easily be written to and read from a file.  Numbers take a bit more
effort, since the <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> method only returns strings, which will have to
be passed to a function like <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a>, which takes a string like <code class="docutils literal notranslate"><span class="pre">'123'</span></code>
and returns its numeric value 123.  When you want to save more complex data
types like nested lists and dictionaries, parsing and serializing by hand
becomes complicated.</p>
<p>Rather than having users constantly writing and debugging code to save
complicated data types to files, Python allows you to use the popular data
interchange format called <a class="reference external" href="http://json.org">JSON (JavaScript Object Notation)</a>.  The standard module called <a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> can take Python
data hierarchies, and convert them to string representations; this process is
called <em class="dfn">serializing</em>.  Reconstructing the data from the string representation
is called <em class="dfn">deserializing</em>.  Between serializing and deserializing, the
string representing the object may have been stored in a file or data, or
sent over a network connection to some distant machine.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>The JSON format is commonly used by modern applications to allow for data
exchange.  Many programmers are already familiar with it, which makes
it a good choice for interoperability.</p>
</div>
<p>If you have an object <code class="docutils literal notranslate"><span class="pre">x</span></code>, you can view its JSON string representation with a
simple line of code:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">json</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">json</span><span class="o">.</span><span class="n">dumps</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;simple&#39;</span><span class="p">,</span> <span class="s1">&#39;list&#39;</span><span class="p">])</span>
<span class="go">&#39;[1, &quot;simple&quot;, &quot;list&quot;]&#39;</span>
</pre></div>
</div>
<p>Another variant of the <a class="reference internal" href="../library/json.html#json.dumps" title="json.dumps"><code class="xref py py-func docutils literal notranslate"><span class="pre">dumps()</span></code></a> function, called <a class="reference internal" href="../library/json.html#json.dump" title="json.dump"><code class="xref py py-func docutils literal notranslate"><span class="pre">dump()</span></code></a>,
simply serializes the object to a <a class="reference internal" href="../glossary.html#term-text-file"><span class="xref std std-term">text file</span></a>.  So if <code class="docutils literal notranslate"><span class="pre">f</span></code> is a
<a class="reference internal" href="../glossary.html#term-text-file"><span class="xref std std-term">text file</span></a> object opened for writing, we can do this:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">json</span><span class="o">.</span><span class="n">dump</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">f</span><span class="p">)</span>
</pre></div>
</div>
<p>To decode the object again, if <code class="docutils literal notranslate"><span class="pre">f</span></code> is a <a class="reference internal" href="../glossary.html#term-text-file"><span class="xref std std-term">text file</span></a> object which has
been opened for reading:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="n">json</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
</pre></div>
</div>
<p>This simple serialization technique can handle lists and dictionaries, but
serializing arbitrary class instances in JSON requires a bit of extra effort.
The reference for the <a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> module contains an explanation of this.</p>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<p><a class="reference internal" href="../library/pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> - the pickle module</p>
<p>Contrary to <a class="reference internal" href="#tut-json"><span class="std std-ref">JSON</span></a>, <em>pickle</em> is a protocol which allows
the serialization of arbitrarily complex Python objects.  As such, it is
specific to Python and cannot be used to communicate with applications
written in other languages.  It is also insecure by default:
deserializing pickle data coming from an untrusted source can execute
arbitrary code, if the data was crafted by a skilled attacker.</p>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">7. Input and Output</a><ul>
<li><a class="reference internal" href="#fancier-output-formatting">7.1. Fancier Output Formatting</a><ul>
<li><a class="reference internal" href="#formatted-string-literals">7.1.1. Formatted String Literals</a></li>
<li><a class="reference internal" href="#the-string-format-method">7.1.2. The String format() Method</a></li>
<li><a class="reference internal" href="#manual-string-formatting">7.1.3. Manual String Formatting</a></li>
<li><a class="reference internal" href="#old-string-formatting">7.1.4. Old string formatting</a></li>
</ul>
</li>
<li><a class="reference internal" href="#reading-and-writing-files">7.2. Reading and Writing Files</a><ul>
<li><a class="reference internal" href="#methods-of-file-objects">7.2.1. Methods of File Objects</a></li>
<li><a class="reference internal" href="#saving-structured-data-with-json">7.2.2. Saving structured data with <code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="modules.html"
                        title="previous chapter"><span class="section-number">6. </span>Modules</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="errors.html"
                        title="next chapter"><span class="section-number">8. </span>Errors and Exceptions</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../bugs.html">Report a Bug</a></li>
      <li>
        <a href="https://github.com/python/cpython/blob/3.8/Doc/tutorial/inputoutput.rst"
            rel="nofollow">Show Source
        </a>
      </li>
    </ul>
  </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="errors.html" title="8. Errors and Exceptions"
             >next</a> |</li>
        <li class="right" >
          <a href="modules.html" title="6. Modules"
             >previous</a> |</li>

          <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
          <li><a href="https://www.python.org/">Python</a> &#187;</li>
          <li class="switchers">
            <div class="language_switcher_placeholder"></div>
            <div class="version_switcher_placeholder"></div>
          </li>
          <li>
              
          </li>
    <li id="cpython-language-and-version">
      <a href="../index.html">3.8.13 Documentation</a> &#187;
    </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li>
                <li class="right">
                    

    <div class="inline-search" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="Quick search" aria-label="Quick search" type="text" name="q" />
          <input type="submit" value="Go" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
                     |
                </li>
            
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 2001-2022, Python Software Foundation.
    <br />
    This page is licensed under the Python Software Foundation License Version 2.
    <br />
    Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
    <br />
    
    <br />

    The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
    <br />

    Last updated on Mar 17, 2022.
    <a href="https://docs.python.org/3/bugs.html">Found a bug</a>?
    <br />

    Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 2.4.4.
    </div>

  </body>
</html>